package com.dony.shop.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dony.common.utils.SecurityUtils;
import com.dony.common.utils.StringUtils;
import com.dony.common.utils.bean.BeanUtils;
import com.dony.shop.domain.GlobalProduct;
import com.dony.shop.domain.Item;
import com.dony.shop.domain.ItemModel;
import com.dony.shop.domain.vo.PriceVo;
import com.dony.shop.domain.vo.ProductVo;
import com.dony.shop.domain.vo.PublishShopVo;
import com.dony.shop.mapper.GlobalProductMapper;
import com.dony.shop.service.IDiscountService;
import com.dony.shop.service.IGlobalModelService;
import com.dony.shop.service.IGlobalProductService;
import com.dony.shop.service.IProductService;
import com.dony.shop.util.PriceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全球商品业务层处理
 *
 * @author sundw
 * @date 2022-03-08
 */
@Slf4j
@Service("productService")
public class ProductServiceImpl extends ServiceImpl<GlobalProductMapper, GlobalProduct> implements IProductService {

    @Resource
    IGlobalModelService globalModelService;
    @Resource
    IGlobalProductService globalProductService;
    @Resource
    IDiscountService discountService;
    @Resource
    ThreadPoolTaskExecutor executor;

    @Override
    public List<GlobalProduct> listByParam(ProductVo productVo) {
        LambdaQueryWrapper<GlobalProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GlobalProduct::getMerchantId, productVo.getMerchantId());
        if (StringUtils.isNotEmpty(productVo.getGlobalItemName())) {
            wrapper.and(w -> {
                w.eq(GlobalProduct::getGlobalItemId, productVo.getGlobalItemName().trim())
                        .or()
                        .like(GlobalProduct::getGlobalItemName, productVo.getGlobalItemName().trim());
            });
        }
        if (StringUtils.isNotEmpty(productVo.getGlobalItemSku())) {
            wrapper.like(GlobalProduct::getGlobalItemSku, productVo.getGlobalItemSku());
        }
        //匹配租户ID
        wrapper.eq(GlobalProduct::getTenantId, SecurityUtils.getDeptId());
        wrapper.orderByDesc(GlobalProduct::getUpdateTime);
        return list(wrapper);
    }


    @Override
    public List<ProductVo> handleProdcutList(List<GlobalProduct> pros) {
        return pros.stream().map(globalProduct -> {
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(globalProduct, productVo);
            //获取价格map
            Map<Float, StringBuilder> priceMap = globalModelService.getPriceMap(productVo.getGlobalItemId());
            //获取现在已经发布店铺的价格
            List<PriceVo> priceVoList = new ArrayList<>();
            priceMap.forEach((k, v) -> {
                PriceVo priceVo = new PriceVo();
                //这是设置全球价格备用
                priceVo.setGlobalPrice(k);
                priceVo.setSkuStr(v.toString());
                priceVo.setWeight(productVo.getWeight());
                priceVo.setOrigenPrice(PriceUtil.getPriceByName(productVo.getGlobalItemSku()));
                priceVo.setGlobalItemId(productVo.getGlobalItemId());
                //分别查询价格
//                if (needPrice) {
//                    priceVo = setContryPrice(productVo.getMerchantId(), priceVo);
//                }
                //封装
                priceVoList.add(priceVo);
            });
            productVo.setPrices(priceVoList);
            return productVo;
        }).collect(Collectors.toList());
    }

    @Override
    public PriceVo getComputePrice(PriceVo priceVo) {
        return globalProductService.setContryPrice(null, priceVo);
    }

    @Override
    public Boolean changePrice(List<ProductVo> products) {
        for (ProductVo pro : products) {
            executor.execute(() -> {
                changePrice(pro);
            });
        }
        return true;
    }

    @Override
    public Boolean changeSinglePrice(Item item) {
        Map<Float, Float> priceMap = new HashMap<>();
        if (item != null && item.getItemModelList() != null && item.getItemModelList().size() > 0) {
            for (ItemModel model : item.getItemModelList()) {
                priceMap.put(model.getOriginalPrice(), model.getCurrentPrice());
            }
        }
        if (priceMap.isEmpty()) {
            return false;
        }
        return discountService.changeItemPrice(item,priceMap);

    }


    /**
     * 修改价格
     *
     * @param productVo
     * @return
     */
    public boolean changePrice(ProductVo productVo) {
        //把价格表放入map中
        Map<Float, JSONObject> allPriceMap = new HashMap<>();
        for (PriceVo price : productVo.getPrices()) {
            allPriceMap.put(price.getGlobalPrice(), globalProductService.getPriceJo(price));
        }
        //获取需要修改店铺的列表
        List<PublishShopVo> shopList = globalProductService.getPulishedShop(productVo.getMerchantId(), productVo.getGlobalItemId());
        //修改价格
        for (PublishShopVo shop : shopList) {
            if (shop.getStatus() == 0) {
                continue;
            }
            //获取单个店铺的价格表
            Map<Float, Float> priceMap = new HashMap<>();
            for (Map.Entry<Float, JSONObject> entry : allPriceMap.entrySet()) {
                priceMap.put(entry.getKey(), entry.getValue().getFloat(shop.getShopRegion().toLowerCase()));
            }
            discountService.changeDiscountPrice(shop.getShopId(), shop.getItemId(), priceMap);
        }
        return true;
    }

}
